package com.example.shop.controller;

import com.example.shop.bean.CartBean;
import com.example.shop.mapper.CartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    CartMapper cartMapper;
    //添加购物车
    @ResponseBody
    @RequestMapping("/add")
    public String cartAdd(CartBean bean){
        List<CartBean> cartL=new ArrayList<>();
        cartL=cartMapper.cartSelByPidUid(bean.pid,bean.uid);

        if(cartL.size()<=0){
            try{

                cartMapper.insert(bean);
                return "1a";
            }catch (Exception e){
                System.out.println("添加购物车出错");
                return "0";
            }
        }else{
           cartL.get(0).count+=bean.count;
            try {
                cartMapper.updateById(cartL.get(0));
                return "1b";
            }catch (Exception e){
                System.out.println("添加购物车出错");
                return "0";
            }
        }

    }

    //查询购物车
    @ResponseBody
    @RequestMapping("/list")
    public List<CartBean> cartList(Integer uid){
        List<CartBean> cartL=new ArrayList<CartBean>();
        cartL= cartMapper.cartSelByUid(uid);
        return cartL;
    }
    //删除购物车
    @ResponseBody
    @RequestMapping("/del")
    public String cartDel(Integer id){
        try{
            cartMapper.deleteById(id);
            return "1";
        }catch (Exception e){
            System.out.println("删除购物车失败");
            return "0";

        }

    }
}
